//让node能连接上MySQL
const mysql = require('mysql');
const config = require('../utils/index.js')

// 创建线程池
const pool =mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password : config.database.PASSWORD,
  database : config.database.DATABASE,
  port : config.database.PORT
})

// 连接数据库，执行sql语句
const allService = {
  query : function (sql,values) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err,connection)=>{ //连接数据库
        
        if (err) {
          console.log(err);
          reject(err)
        }else {//连接成功
          console.log(12312321312);
          connection.query(sql,values,(err,rows)=>{//执行sql语句
            if (err) {
              reject(err)
            }else { // sql 语句执行成功
              resolve(rows)
            }
            connection.release()//断开连接
          })
        } 

      })
    })
  }
}

//推荐页按照sort 这个字段寻找数据
const findRecommend = (sort) =>{
  let _sql = `select * from recommend where sort="${sort}"`
  return allService.query(_sql)
}
// 用户主页的自己发的穿搭
const findUserRecommend = (userId) =>{
  let _sql = `select * from recommend where userId="${userId}"`
  return allService.query(_sql)
}


//detail 详情页通过 picId 字段 拿到图片库数据
const findpicture = (picId) =>{
  let _sql = `select * from picture where picId="${picId}"`
  return allService.query(_sql)
}

//进入 详情页通过 detailId 拿到详情页数据
const findDetail = (detailId) => {
  let _sql = `select * from detail where detailId="${detailId}"`
  return allService.query(_sql)
}

// 登录
const userLogin = (phone, password) =>{
  let _sql =  `select * from user where phone="${phone}" and password="${password}"`
  return allService.query(_sql)
}

//通过userId 拿到数据
const  getUserData = (userId) =>{
  let _sql = `select * from user where userId="${userId}"`
  return allService.query(_sql)
}

// 创作内容

// 写入图片库
const writePic = (values) =>{
  let _sql = `insert into picture set picId=?,pic_1=?,pic_2=?,pic_3=?,pic_4=?,
  pic_5=?,pic_6=?,pic_7=?,pic_8=?,pic_9=?`
  return allService.query(_sql,values)
}
//写入推荐库
const writeRec = (values) =>{
  let _sql = `insert into recommend set userId=?,userName=?,userProfilePhoto=?
  ,userSignature=?,picId=?,detailId=?,head=?,serachKey=?`
  return allService.query(_sql,values)
}
//写入详情库
const writeDet = (values) =>{
  let _sql = `insert into detail set detailId=?,title=?,content=?,userId=?`
  return allService.query(_sql,values)
}



module.exports = {
  findRecommend,
  findpicture,
  findDetail,
  userLogin,
  getUserData,
  findUserRecommend,

  writePic,
  writeRec,
  writeDet
}